import { prisma } from "@src/common/database"
import { DatabaseUtils } from "@src/common/db-utils"
import type { User, UserRole, UserStatus } from "@prisma/client"

/**
 * 用户服务类
 * 提供用户相关的业务逻辑
 */
export class UserService {
  /**
   * 根据ID获取用户
   */
  static async getUserById(id: bigint): Promise<User | null> {
    return await prisma.user.findUnique({
      where: { id },
    })
  }

  /**
   * 根据邮箱获取用户
   */
  static async getUserByEmail(email: string): Promise<User | null> {
    return await prisma.user.findUnique({
      where: { email },
    })
  }

  /**
   * 创建新用户
   */
  static async createUser(data: {
    loginId: string
    email: string
    passwordHash: string
    role?: UserRole
    avatarUrl?: string
    name?: string
    nickname?: string
    phone?: string
    gender?: string
    birthdate?: Date
    referrerId?: bigint
  }): Promise<User> {
    const user = await prisma.user.create({
      data: {
        loginId: data.loginId,
        email: data.email,
        passwordHash: data.passwordHash,
        role: data.role || "user",
        avatarUrl: data.avatarUrl,
        name: data.name,
        nickname: data.nickname,
        phone: data.phone,
        gender: data.gender,
        birthdate: data.birthdate,
        referrerId: data.referrerId,
      },
    })

    // 创建用户钱包
    await DatabaseUtils.createUserWalletIfNotExists(user.id)

    return user
  }

  /**
   * 更新用户信息
   */
  static async updateUser(id: bigint, data: Partial<Pick<User, "email" | "role" | "status" | "avatarUrl">>): Promise<User> {
    return await prisma.user.update({
      where: { id },
      data,
    })
  }

  /**
   * 删除用户
   */
  static async deleteUser(id: bigint): Promise<User> {
    return await prisma.user.delete({
      where: { id },
    })
  }

  /**
   * 获取用户列表（分页）
   */
  static async getUsers(params: { page?: number; limit?: number; role?: UserRole; status?: UserStatus; search?: string }) {
    const { page = 1, limit = 20, role, status, search } = params
    const { skip, take } = DatabaseUtils.getPaginationParams(page, limit)

    const where: any = {}

    if (role) {
      where.role = role
    }

    if (status) {
      where.status = status
    }

    if (search) {
      where.email = {
        contains: search,
        mode: "insensitive",
      }
    }

    const [users, total] = await Promise.all([
      prisma.user.findMany({
        where,
        skip,
        take,
        orderBy: { createdAt: "desc" },
        select: {
          id: true,
          email: true,
          role: true,
          status: true,
          avatarUrl: true,
          createdAt: true,
        },
      }),
      prisma.user.count({ where }),
    ])

    return DatabaseUtils.buildPaginationResponse(users, total, page, limit)
  }

  /**
   * 获取用户详细信息（包含钱包）
   */
  static async getUserDetails(id: bigint) {
    return await DatabaseUtils.getUserWithWallet(id)
  }

  /**
   * 检查邮箱是否已存在
   */
  static async isEmailExists(email: string): Promise<boolean> {
    const user = await prisma.user.findUnique({
      where: { email },
      select: { id: true },
    })
    return !!user
  }

  /**
   * 更新用户状态
   */
  static async updateUserStatus(id: bigint, status: UserStatus): Promise<User> {
    return await prisma.user.update({
      where: { id },
      data: { status },
    })
  }

  /**
   * 获取管理员用户列表
   */
  static async getAdminUsers() {
    return await prisma.user.findMany({
      where: {
        role: "admin",
        status: "active",
      },
      select: {
        id: true,
        email: true,
        role: true,
        status: true,
        avatarUrl: true,
        createdAt: true,
      },
    })
  }

  /**
   * 获取用户统计信息
   */
  static async getUserStats() {
    const [totalUsers, activeUsers, bannedUsers, adminUsers] = await Promise.all([
      prisma.user.count(),
      prisma.user.count({ where: { status: "active" } }),
      prisma.user.count({ where: { status: "banned" } }),
      prisma.user.count({ where: { role: "admin" } }),
    ])

    return {
      totalUsers,
      activeUsers,
      bannedUsers,
      adminUsers,
    }
  }
}

export default UserService
